using System;
using System.Configuration;
using System.Linq;
using Ninject.Activation;
using Ninject.Planning;
using Ninject.Planning.Directives;
using Ninject.Selection.Heuristics;

namespace ninject.configurer
{
    public class AppSettingsProvider : BaseConfigurationProvider
    {
        public AppSettingsProvider(Type type, IPlanner planner, IConstructorScorer scorer)
            : base(type, planner, scorer)
        {
        }

        public override object Create(IContext context)
        {
            if (context.Plan == null)
                context.Plan = Planner.GetPlan(Type);

            ConstructorInjectionDirective directive =
                (from option in context.Plan.GetAll<ConstructorInjectionDirective>()
                 orderby ConfigurationScorer(context, option) descending
                 select option).First();

            object[] arguments =
                (from target in directive.Targets select ConfigurationManager.AppSettings[target.Name]).ToArray();

            return directive.Injector(arguments);
        }
    }
}